package com.thb.pay.engine.manager;

import com.thb.pay.engine.context.Context;
import groovy.lang.GroovyClassLoader;

import java.lang.reflect.InvocationTargetException;

/**
 * Groovy 单例
 * <p> * https://github.com/dyingbleed/g-rule</p>
 */
public class GroovyManager {
    private static GroovyManager instance = new GroovyManager();
    private GroovyClassLoader groovyClassLoader;

    private GroovyManager() {
        this.groovyClassLoader = new GroovyClassLoader();
    }

    public static GroovyManager getInstance() {
        return instance;
    }

    /**
     * 获取 Groovy 类加载器
     *
     * @return Groovy 类加载器实例
     */
    public GroovyClassLoader getGroovyClassLoader() {
        return this.groovyClassLoader;
    }


    /**
     * @param groovyClass: Groovy 类
     * @param methodName:  方法名
     * @param args:        参数列表
     * @方法名称
     * @功能描述
     * @作者: lucky
     * @创建时间: 20:48 2019/11/5
     * @return: java.lang.Object
     **/
    public Object invokeMethod(Class groovyClass, String methodName, Object... args) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {

        if (groovyClass == null) {
            return null;
        }
        try {
            return groovyClass.getMethod(methodName, Context.class).invoke(groovyClass.newInstance(), args);
        } catch (InstantiationException | InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
            throw e;
        }
    }

}
